package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码
     * @param user
     * @param request
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg (@RequestBody User user, HttpServletRequest request){
        //获取手机号
        String phone = user.getPhone();
        //随机生成的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //调用阿里云提供的短信服务api完成短信息
        log.info(code);
        //需要将生成的验证码保存到session
        request.getSession().setAttribute("code",code);
        return  R.success("手机验证码短信发送成功");
    }
    @PostMapping("login")
    public  R<User> login( @RequestBody Map<String,String> map,HttpServletRequest request){
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code = map.get("code");
        //session中获取保存的验证码
        String code1 = (String) request.getSession().getAttribute("code");
        //进行验证码的对比
        if (!StringUtils.equals(code,code1)){
           return R.error("验证码错误");
        }
        //判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if (user==null){
            //新用户注册
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        //将用户存入session中
        request.getSession().setAttribute("user",user.getId());
        return  R.success(user);
    }
}
